//
//  ViewController.m
//  BTDemo
//
//  Created by 李松芮 on 2018/2/1.
//  Copyright © 2018年 李松芮. All rights reserved.
//

#import "ViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>

@interface ViewController () <CBCentralManagerDelegate, CBPeripheralDelegate>

@property (weak, nonatomic) IBOutlet UILabel *stateLabel;
@property (nonatomic, strong) CBCentralManager *peripheralManager;
@property (nonatomic, strong) CBPeripheral *peripheral;
@property (nonatomic, strong) CBCharacteristic *characteristic;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    _stateLabel.text = @"wait";
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - action

- (IBAction)startSearch:(UIButton *)sender {
    
    if (!_peripheralManager) {
        _peripheralManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue() options:@{}];
    }
    _stateLabel.text = @"initial";
    if (_peripheralManager.state == CBCentralManagerStatePoweredOn) {
        // normal
        [self startScan];
    }
}

- (void)startScan
{
    _stateLabel.text = @"scanning";
    // TODO:可以设置service uuid
//    CBUUID *uuid = [CBUUID UUIDWithString:@"xxxx-xxxx-xxxx-xxxx"];
//    NSArray *uuidArray = @[uuid];
    [_peripheralManager scanForPeripheralsWithServices:nil options:@{}];
}

- (IBAction)sendData:(UIButton *)sender
{
    if (self.peripheral) {
        NSString *sendText = @"test";
        NSData *senddata = [sendText dataUsingEncoding:NSUTF8StringEncoding];
        
        [self.peripheral writeValue:senddata forCharacteristic:self.characteristic type:CBCharacteristicWriteWithoutResponse];
    }
}

- (IBAction)disconnect:(UIButton *)sender
{
    if (self.peripheralManager) {
        _stateLabel.text = @"disconnecting";
        [self.peripheralManager cancelPeripheralConnection:self.peripheral];
    }
}

#pragma mark - CBCentralManagerDelegate

- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    if (central.state == CBCentralManagerStatePoweredOn) {
        // normal
        [self startScan];
    }
    else if (central.state == CBCentralManagerStateUnauthorized) {
        _stateLabel.text = @"unauthorized";
    }
    else {
        _stateLabel.text = @"not available";
    }
}

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *, id> *)advertisementData RSSI:(NSNumber *)RSSI;
{
    _stateLabel.text = @"found device";
    [central stopScan]; // 停止搜索(optionnal)
    [central connectPeripheral:peripheral options:@{}]; // 连接设备
}

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    _stateLabel.text = @"connected";
    peripheral.delegate = self;
    [peripheral discoverServices:nil]; // 发现服务
    self.peripheral = peripheral;
}

- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error
{
    _stateLabel.text = @"connnect failed";
}

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error
{
    _stateLabel.text = @"disconnected";
    self.peripheral = nil;
    self.characteristic = nil;
}

#pragma mark - CBPeripheralDelegate

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
    for (CBCharacteristic *character in service.characteristics) {
        if ([character.UUID.UUIDString isEqualToString:@"xxxx-xxxx"]) {
            self.characteristic = character;
            _stateLabel.text = @"characteristic found";
            return;
        }
    }
    _stateLabel.text = @"service characteristic not found";
}

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    _stateLabel.text = @"data received";
}

 - (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error
{
    if (error) {
        _stateLabel.text = [NSString stringWithFormat:@"send failed:%@", error];
    }
    else {
        _stateLabel.text = @"data sended";
    }
}

@end
